##
## Menu.py v0.1
##
## Generates the Menu
##
## Author: Shannon Eric Peevey <speeves@erikin.com>, 23 March 2005
##
import Pgenerate
import re, md5

# Try to import the optional modules
try:
    from Mssql import *
except ImportError:
    pass
try:
    from Mysql import *
except ImportError:
    pass
try:
    from Htgroup import *
except ImportError:
    pass
try:
    from Webcontrol import *
except ImportError:
    pass
try:
    from Email import *
except ImportError:
    pass
try:
    from Postgresql import *
except ImportError:
    pass
try:
    from Analog import *
except ImportError:
    pass
try:
    from Ldap import *
except ImportError:
    pass
try:
    from Utility import *
except ImportError:
    pass
try:
    from Wizard import *
except ImportError:
    pass

class MenuFunc:
    """Generates the command line menu for cwsAdmin"""
    def MenuCreate(self, config, menu, errorObject, utilityObject):
        """ Generate the XML menu for menu driven usage of cwsAdmin """
        # variables for iteration and defining the top menu
        showItem = 0
        choice = -1
        place = 2
        numberOfItems = 0
        topMenu = menu.childNodes
        menu = menu.childNodes
        prevMenu = topMenu
        while place != 1:
            for menuEntry in menu:
                if menuEntry.nodeName == 'menuEntry':
                    try:
                        # Check to see if childNodes[5].nodeName == 'child'
                        # Meaning it is a MenuItem with functions under it.
                        if menuEntry.childNodes[5].nodeName != '':
                            if menuEntry.childNodes[5].nodeName == 'child':
                                showItem = 1
                            else:
                                try:
                                    nodeEntryClassName = menuEntry.childNodes[5].firstChild.data
                                    # Test to see if dict["useDict"] == '1'
                                    for name in config['General']['confDictNames']:
                                        dictName = name + "Dict"
                                        funcName = name.title() + "Func"
                                        dictNameValue = dictName + '["use' + name.title() + '"]'
                                        ## DEBUGGING
                                        if config['General']["debugLevel"] == '5':
                                            print "\nname == ", name
                                            print "dictName == ", dictName
                                            print "funcName == ", funcName
                                            print "nodeEntryClassName == ", nodeEntryClassName
                                            print dictName + '["use' + name.title() + '"]'
                                            print "dictNameValue == ", dictNameValue
                                            print "showItem == ", showItem
                                            print "\n"

                                        # Check if nodeEntryClassName == funcName
                                        # Then check if the dictName['useDict'] == '1'.
                                        if nodeEntryClassName == funcName and eval(dictNameValue) == '1': 
                                            showItem = 1
                                            break
                                        else:
                                            showItem = 0
                                except:
                                    print "Invalid Option"
                                    errorObject.InvalidOptionError()
                                    continue

                    except:
                        # This entry doesn't have childNodes[5]
                        # Meaning it is a Previous Menu entry
                        showItem = 1

                    ## DEBUGGING
                    if config['General']['debugLevel'] == '5':
                        print "showItem before printing items == ", showItem
                        print menuEntry.childNodes[1].toxml()

                    # Print out the Menu Items
                    if showItem == 1:
                        item = menuEntry.childNodes[1]
                        value = menuEntry.childNodes[3]
                        print "(" + item.firstChild.data + ") " + value.firstChild.data
                        numberOfItems += 1
                showItem = 0

            choice = raw_input("Which item would you like to choose? (m => Main Menu, q => Quit) ")

            # if q or m, then change to equivalent integer
            if choice == 'q':
                choice = -3
            elif choice == 'm':
                choice = -2

            # For some reason, on the first load of the main menu, we need to add 1 to get the
            # last menu item... (BUG??)
            numberOfItems += 1

            # test to see if choice has an integer value
            try:
                int(choice)
                choice = int(choice)
            except:
                print "Invalid Option"
                errorObject.InvalidOptionError()
                continue

            if choice >= numberOfItems:
                print "The choice >= numberOfItems"
                errorObject.InvalidOptionError()
                continue
            elif choice == -3:
                place = 1
            elif choice == -2:
                place = 2
                menu = topMenu
            elif choice <= 1:
                place = place - 1
                if place == 2:
                    menu = topMenu
                else:
                    menu = prevMenu
            elif choice >= 1:
                place = place + 1
                # prevMenu = prevMenu

                ###  needs to be [choice + (choice - 1)]
                # to deal with the text nodes in the XML
                if menu[choice + (choice - 1)].childNodes[5]:
                    if menu[choice + (choice - 1)].childNodes[5].nodeName == 'className':
                        # get the data for function calls
                        className = menu[choice + (choice - 1)].childNodes[5].firstChild
                        functionName =  menu[choice + (choice - 1)].childNodes[7].firstChild
                        arguments =  menu[choice + (choice - 1)].childNodes[9].firstChild

                        # create strings to call functions
                        createInstance = "execcommand = " + className.data + "()"
                        runFunc = "execcommand." + functionName.data + "(" + arguments.data + ")" 
                        deleteInstance = "del execcommand"

                        ## DEBUGGING
                        if config['General']['debugLevel'] == '5':
                            print "createInstance == ", createInstance
                            print "runFunc == ", runFunc
                            print "deleteInstance == ", deleteInstance

                        # compile strings to run functions
                        y = compile(createInstance,'','exec')
                        yz = compile(runFunc,'','exec')
                        z = compile(deleteInstance,'','exec')                  

                        # execute strings
                        exec y
                        exec yz
                        exec z
                    else:
                        prevMenu = menu
                        menu = menu[choice + (choice - 1)].childNodes[5].childNodes




              
#     def OutputToLogFile(self, genDict, ):
#         """  """
#         newSkelLines = ""
#         for eachline in skelLines:
#             count = 0
#             for key, value in skelDict.items():
#                 if re.compile(key).match(key):
#                     eachline = re.sub(key, value, eachline)

#             newSkelLines = newSkelLines + eachline
                
#         return newSkelLines
